package com.dcs.cn.item.controller;


import cn.com.dcsgo.api.client.ItemClient;
import cn.com.dcsgo.aspect.ApiOperationLog;
import cn.com.dcsgo.domain.dto.PageDTO;
import cn.com.dcsgo.exception.BadRequestException;
import cn.com.dcsgo.exception.BizIllegalException;
import cn.com.dcsgo.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.com.dcsgo.api.dto.ItemDTO;
import cn.com.dcsgo.api.dto.OrderDetailDTO;
import com.dcs.cn.item.domain.po.Item;
import com.dcs.cn.item.domain.query.ItemPageQuery;
import com.dcs.cn.item.enums.ItemStatus;
import com.dcs.cn.item.service.IItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Api(tags = "商品管理相关接口")
@RestController
@RequestMapping("/items")
@RequiredArgsConstructor
public class ItemController {

    private final IItemService itemService;

    private final ItemClient itemClient;

    @ApiOperation("分页查询商品")
    @ApiOperationLog(description = "分页查询商品")
    @GetMapping("/page")
    public PageDTO<ItemDTO> queryItemByPage(ItemPageQuery query) {
        // 1.分页查询
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<Item>()
                .like(StrUtil.isNotBlank(query.getKey()), Item::getName, query.getKey())
                .eq(StrUtil.isNotBlank(query.getBrand()), Item::getBrand, query.getBrand())
                .eq(StrUtil.isNotBlank(query.getCategory()), Item::getCategory, query.getCategory())
                .eq(Item::getStatus, ItemStatus.NORMAL.getCode())
                .between(query.getMaxPrice() != null, Item::getPrice, query.getMinPrice(), query.getMaxPrice());
        Page<Item> result = itemService.page(query.toMpPage("update_time", false), queryWrapper);
        // 2.封装并返回
        return PageDTO.of(result, ItemDTO.class);
    }

    @ApiOperation("根据id批量查询商品")
    @ApiOperationLog(description = "根据id批量查询商品")
    @GetMapping
    public List<ItemDTO> queryItemByIds(@RequestParam("ids") List<Long> ids){
        throw new BadRequestException("请使用feign调用");
//        return itemService.queryItemByIds(ids);
    }

    @ApiOperation("根据id查询商品")
    @ApiOperationLog(description = "根据id查询商品")
    @GetMapping("{id}")
    public ItemDTO queryItemById(@PathVariable("id") Long id) {
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<Item>()
                .eq(Item::getStatus, ItemStatus.NORMAL.getCode())
                .eq(Item::getId, id);
        return BeanUtils.copyBean(itemService.getOne(queryWrapper), ItemDTO.class);
    }

    @ApiOperation("新增商品")
    @ApiOperationLog(description = "新增商品")
    @PostMapping
    public void saveItem(@RequestBody ItemDTO item) {
        // 新增
        itemService.save(BeanUtils.copyBean(item, Item.class));
    }

    @ApiOperation("更新商品状态")
    @ApiOperationLog(description = "更新商品状态")
    @PutMapping("/status/{id}/{status}")
    public void updateItemStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status){
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
    }

    @ApiOperation("更新商品")
    @ApiOperationLog(description = "更新商品")
    @PutMapping
    public void updateItem(@RequestBody ItemDTO item) {
        // 不允许修改商品状态，所以强制设置为null，更新时，就会忽略该字段
        item.setStatus(null);
        // 更新
        itemService.updateById(BeanUtils.copyBean(item, Item.class));
    }

    @ApiOperation("根据id删除商品")
    @ApiOperationLog(description = "根据id删除商品")
    @DeleteMapping("{id}")
    public void deleteItemById(@PathVariable("id") Long id) {
        // 逻辑删除
        // 避免出现商品误删的情况
        Item item = new Item();
        item.setId(id);
        item.setStatus(ItemStatus.DELETED.getCode());
        itemService.updateById(item);
    }

    @ApiOperation("批量扣减库存")
    @ApiOperationLog(description = "批量扣减库存")
    @PutMapping("/items/stock/deduct")
    public void deductStock(@RequestBody List<OrderDetailDTO> items){
        itemService.deductStock(items);
    }

    @ApiOperation("批量添加库存")
    @ApiOperationLog(description = "批量添加库存")
    @PutMapping("/items/stock/add/")
    public void addStock(@RequestBody List<OrderDetailDTO> items){
        itemService.addStock(items);
    }

    /**
     * 根据商品id获取库存
     */
    @ApiOperation("根据商品id获取库存")
    @ApiOperationLog(description = "根据商品id获取库存")
    @GetMapping("/stock/{id}")
    public Integer getStockById(@PathVariable("id") Long id) throws InterruptedException {
        Thread.sleep(1000);
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<Item>()
                .eq(Item::getStatus, ItemStatus.NORMAL.getCode())
                .eq(Item::getId, id);
        Item item = itemService.getOne(queryWrapper);
        if (item == null) {
            throw new BizIllegalException("商品不存在");
        }
        return item.getStock();
    }
}
